/*
 * Copyright 2002-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.springframework.aop.framework.autoproxy;

import org.aopalliance.aop.Advice;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.aop.Advisor;
import org.springframework.aop.Pointcut;
import org.springframework.aop.TargetSource;
import org.springframework.aop.framework.AopInfrastructureBean;
import org.springframework.aop.framework.ProxyFactory;
import org.springframework.aop.framework.ProxyProcessorSupport;
import org.springframework.aop.framework.adapter.AdvisorAdapterRegistry;
import org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry;
import org.springframework.aop.target.SingletonTargetSource;
import org.springframework.beans.BeansException;
import org.springframework.beans.PropertyValues;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor;
import org.springframework.lang.Nullable;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.lang.reflect.Constructor;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
 * that wraps each eligible bean with an AOP proxy, delegating to specified interceptors
 * before invoking the bean itself.
 *
 * <p>This class distinguishes between "common" interceptors: shared for all proxies it
 * creates, and "specific" interceptors: unique per bean instance. There need not be any
 * common interceptors. If there are, they are set using the interceptorNames property.
 * As with {@link org.springframework.aop.framework.ProxyFactoryBean}, interceptors names
 * in the current factory are used rather than bean references to allow correct handling
 * of prototype advisors and interceptors: for example, to support stateful mixins.
 * Any advice type is supported for {@link #setInterceptorNames "interceptorNames"} entries.
 *
 * <p>Such auto-proxying is particularly useful if there's a large number of beans that
 * need to be wrapped with similar proxies, i.e. delegating to the same interceptors.
 * Instead of x repetitive proxy definitions for x target beans, you can register
 * one single such post processor with the bean factory to achieve the same effect.
 *
 * <p>Subclasses can apply any strategy to decide if a bean is to be proxied, e.g. by type,
 * by name, by definition details, etc. They can also return additional interceptors that
 * should just be applied to the specific bean instance. A simple concrete implementation is
 * {@link BeanNameAutoProxyCreator}, identifying the beans to be proxied via given names.
 *
 * <p>Any number of {@link TargetSourceCreator} implementations can be used to create
 * a custom target source: for example, to pool prototype objects. Auto-proxying will
 * occur even if there is no advice, as long as a TargetSourceCreator specifies a custom
 * {@link org.springframework.aop.TargetSource}. If there are no TargetSourceCreators set,
 * or if none matches, a {@link org.springframework.aop.target.SingletonTargetSource}
 * will be used by default to wrap the target bean instance.
 *
 * @author Juergen Hoeller
 * @author Rod Johnson
 * @author Rob Harrop
 * @since 13.10.2003
 * @see #setInterceptorNames
 * @see #getAdvicesAndAdvisorsForBean
 * @see BeanNameAutoProxyCreator
 * @see DefaultAdvisorAutoProxyCreator
 */
@SuppressWarnings("serial")
public abstract class AbstractAutoProxyCreator extends ProxyProcessorSupport
		implements SmartInstantiationAwareBeanPostProcessor, BeanFactoryAware {

	/**
	 * Convenience constant for subclasses: Return value for "do not proxy".
	 * @see #getAdvicesAndAdvisorsForBean
	 */
	@Nullable
	protected static final Object[] DO_NOT_PROXY = null;

	/**
	 * Convenience constant for subclasses: Return value for
	 * "proxy without additional interceptors, just the common ones".
	 * @see #getAdvicesAndAdvisorsForBean
	 */
	protected static final Object[] PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS = new Object[0];


	/** Logger available to subclasses. */
	protected final Log logger = LogFactory.getLog(getClass());

	/** Default is global AdvisorAdapterRegistry. */
	private AdvisorAdapterRegistry advisorAdapterRegistry = GlobalAdvisorAdapterRegistry.getInstance();

	/**
	 * Indicates whether or not the proxy should be frozen. Overridden from super
	 * to prevent the configuration from becoming frozen too early.
	 */
	private boolean freezeProxy = false;

	/** Default is no common interceptors. */
	private String[] interceptorNames = new String[0];

	private boolean applyCommonInterceptorsFirst = true;

	@Nullable
	private TargetSourceCreator[] customTargetSourceCreators;

	@Nullable
	private BeanFactory beanFactory;

	private final Set<String> targetSourcedBeans = Collections.newSetFromMap(new ConcurrentHashMap<>(16));

	/** 用来记录某个原始对象是否进行过AOP了 */
	private final Map<Object, Object> earlyProxyReferences = new ConcurrentHashMap<>(16);

	private final Map<Object, Class<?>> proxyTypes = new ConcurrentHashMap<>(16);

	private final Map<Object, Boolean> advisedBeans = new ConcurrentHashMap<>(256);


	/**
	 * Set whether or not the proxy should be frozen, preventing advice
	 * from being added to it once it is created.
	 * <p>Overridden from the super class to prevent the proxy configuration
	 * from being frozen before the proxy is created.
	 */
	@Override
	public void setFrozen(boolean frozen) {
		this.freezeProxy = frozen;
	}

	@Override
	public boolean isFrozen() {
		return this.freezeProxy;
	}

	/**
	 * Specify the {@link AdvisorAdapterRegistry} to use.
	 * <p>Default is the global {@link AdvisorAdapterRegistry}.
	 * @see org.springframework.aop.framework.adapter.GlobalAdvisorAdapterRegistry
	 */
	public void setAdvisorAdapterRegistry(AdvisorAdapterRegistry advisorAdapterRegistry) {
		this.advisorAdapterRegistry = advisorAdapterRegistry;
	}

	/**
	 * Set custom {@code TargetSourceCreators} to be applied in this order.
	 * If the list is empty, or they all return null, a {@link SingletonTargetSource}
	 * will be created for each bean.
	 * <p>Note that TargetSourceCreators will kick in even for target beans
	 * where no advices or advisors have been found. If a {@code TargetSourceCreator}
	 * returns a {@link TargetSource} for a specific bean, that bean will be proxied
	 * in any case.
	 * <p>{@code TargetSourceCreators} can only be invoked if this post processor is used
	 * in a {@link BeanFactory} and its {@link BeanFactoryAware} callback is triggered.
	 * @param targetSourceCreators the list of {@code TargetSourceCreators}.
	 * Ordering is significant: The {@code TargetSource} returned from the first matching
	 * {@code TargetSourceCreator} (that is, the first that returns non-null) will be used.
	 */
	public void setCustomTargetSourceCreators(TargetSourceCreator... targetSourceCreators) {
		this.customTargetSourceCreators = targetSourceCreators;
	}

	/**
	 * Set the common interceptors. These must be bean names in the current factory.
	 * They can be of any advice or advisor type Spring supports.
	 * <p>If this property isn't set, there will be zero common interceptors.
	 * This is perfectly valid, if "specific" interceptors such as matching
	 * Advisors are all we want.
	 */
	public void setInterceptorNames(String... interceptorNames) {
		this.interceptorNames = interceptorNames;
	}

	/**
	 * Set whether the common interceptors should be applied before bean-specific ones.
	 * Default is "true"; else, bean-specific interceptors will get applied first.
	 */
	public void setApplyCommonInterceptorsFirst(boolean applyCommonInterceptorsFirst) {
		this.applyCommonInterceptorsFirst = applyCommonInterceptorsFirst;
	}

	@Override
	public void setBeanFactory(BeanFactory beanFactory) {
		this.beanFactory = beanFactory;
	}

	/**
	 * Return the owning {@link BeanFactory}.
	 * May be {@code null}, as this post-processor doesn't need to belong to a bean factory.
	 */
	@Nullable
	protected BeanFactory getBeanFactory() {
		return this.beanFactory;
	}


	@Override
	@Nullable
	public Class<?> predictBeanType(Class<?> beanClass, String beanName) {
		if (this.proxyTypes.isEmpty()) {
			return null;
		}
		Object cacheKey = getCacheKey(beanClass, beanName);
		return this.proxyTypes.get(cacheKey);
	}

	@Override
	@Nullable
	public Constructor<?>[] determineCandidateConstructors(Class<?> beanClass, String beanName) {
		return null;
	}

	@Override
	public Object getEarlyBeanReference(Object bean, String beanName) {
		Object cacheKey = getCacheKey(bean.getClass(), beanName);
		this.earlyProxyReferences.put(cacheKey, bean);
		return wrapIfNecessary(bean, beanName, cacheKey);
	}

	@Override
	public Object postProcessBeforeInstantiation(Class<?> beanClass, String beanName) {
		// 如果是普通 bean，则返回 beanName，如果是 FactoryBean, 则返回加上前缀 & 的 &beanName
		Object cacheKey = getCacheKey(beanClass, beanName);

		// 判断 TargetSource 缓存中是否包含当前 Bean，如果不包含，则判断当前 Bean 是否是已经被代理的 Bean，
		// 如果代理过，则不对当前传入的 Bean 进行处理，如果没代理过，则判断当前 Bean 是否为系统 Bean，或者是
		// 切面逻辑不会包含的 bean，如果是，则将当前 bean 缓存到 advisedBeans 中，否则继续往下执行。
		// 经过这一步的处理之后，只有在 TargetSource 中没有进行缓存，并且应该被切面逻辑环绕，但是目前还未
		// 生成代理对象的 Bean 才会通过此方法。
		// 第一次进入时，targetSourcedBeans 还未缓存有对象，故会进入。
		if (!StringUtils.hasLength(beanName) || !this.targetSourcedBeans.contains(beanName)) {
			// 如果 this.advisedBeans 有缓存值，说明该 Bean 已经被解析过了，直接返回 null 就跳过了后续的解析
			if (this.advisedBeans.containsKey(cacheKey)) {
				return null;
			}

			/**
			 * @Aspect 切面类类
			 * 判断当前 Bean 是否是基础类型的 Advice、Pointcut、Advisor、AopInfrastructureBean(也就是实现了 Advise 接口的)或者是否是切面（@Aspect）
			 * 给定的 Bean 类是否代表一个基础设施类，基础设施类不应代理,或者配置了指定 Bean 不需要自动代理。
			 * applyBeanPostProcessorsBeforeInstantiation 因为遍历是 AnnotationAwareAspectJAutoProxyCreator，进入 AnnotationAwareAspectJAutoProxyCreator 类的 isInfrastructureClass() 会将 @Aspect注解 的类排除。如：myAspect、aspectJTest、myAroundAdvise
			 */
			if (isInfrastructureClass(beanClass) || shouldSkip(beanClass, beanName)) { // Infrastructure 中文意思是“基础”
				this.advisedBeans.put(cacheKey, Boolean.FALSE);
				return null;
			}
		}

		// Create proxy here if we have a custom TargetSource.
		// Suppresses unnecessary default instantiation of the target bean:
		// The TargetSource will handle target instances in a custom fashion.
		// 如果我们有自定义 TargetSource，请在此处创建代理。禁止目标 bean 的不必要的默认实例化：
		// TargetSource 将以自定义方式处理目标实例。
		// 获取封装当前 Bean 的 TargetSource 对象，如果不存在，则直接退出当前方法，否则从
		// TargetSource 中获取当前 Bean 对象，并且判断是否需要将切面逻辑应用在当前 Bean 上。
		// 如果用户自定义了 TargetSource，那么直接返回用户自定义的代理类。否则返回 null，使得 Spring 框架能继续执行下去。
		TargetSource targetSource = getCustomTargetSource(beanClass, beanName);
		if (targetSource != null) {
			if (StringUtils.hasLength(beanName)) {
				this.targetSourcedBeans.add(beanName);
			}
			// 获取能够应用当前 Bean 的切面逻辑
			Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(beanClass, beanName, targetSource);
			/**
			 * 根据切面逻辑为当前 Bean 生成代理对象
			 */
			Object proxy = createProxy(beanClass, beanName, specificInterceptors, targetSource);
			// 对生成的代理对象进行缓存
			this.proxyTypes.put(cacheKey, proxy.getClass());
			// 直接返回生成的代理对象，从而使后续 Bean 的创建工作短路
			return proxy;
		}

		return null;
	}

	@Override
	public boolean postProcessAfterInstantiation(Object bean, String beanName) {
		return true;
	}

	@Override
	public PropertyValues postProcessProperties(PropertyValues pvs, Object bean, String beanName) {
		return pvs;
	}

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
		return bean;
	}

	/**
	 * Create a proxy with the configured interceptors if the bean is
	 * identified as one to proxy by the subclass.
	 * 如果 bean 被子类标识为代理，则使用配置的拦截器创建一个代理。
	 * @see #getAdvicesAndAdvisorsForBean
	 */
	@Override
	public Object postProcessAfterInitialization(@Nullable Object bean, String beanName) {
		if (bean != null) {
			//根据给定的 bean 的 class 和 name 构建出一个 key，格式: beanClassName_beanName
			Object cacheKey = getCacheKey(bean.getClass(), beanName);
			if (this.earlyProxyReferences.remove(cacheKey) != bean) {
				//如果它适合被代理，则需要封装指定 bean。如果是增强器创建代理，返回代理代理，如果是普通的bean，原生不动返回。
				return wrapIfNecessary(bean, beanName, cacheKey);
			}
		}
		return bean;
	}


	/**
	 * Build a cache key for the given bean class and bean name.
	 * 为给定的 bean 类和 bean 名称构建一个缓存键。
	 * <p>Note: As of 4.2.3, this implementation does not return a concatenated
	 * class/name String anymore but rather the most efficient cache key possible:
	 * a plain bean name, prepended with {@link BeanFactory#FACTORY_BEAN_PREFIX}
	 * in case of a {@code FactoryBean}; or if no bean name specified, then the
	 * given bean {@code Class} as-is.
	 * 注意：从 4.2.3 开始，此实现不再返回连接的类/名称字符串，而是返回最有效的缓存键：
	 * 一个普通的 bean 名称，在 {@code FactoryBean}; 或者如果没有指定 bean 名称，则给定
	 * bean {@code Class} 原样。
	 * @param beanClass the bean class
	 * @param beanName the bean name
	 * @return the cache key for the given class and name
	 */
	protected Object getCacheKey(Class<?> beanClass, @Nullable String beanName) {
		if (StringUtils.hasLength(beanName)) {
			//FACTORY_BEAN_PREFIX = "&";
			return (FactoryBean.class.isAssignableFrom(beanClass) ?
					BeanFactory.FACTORY_BEAN_PREFIX + beanName : beanName); //如果是 FactoryBean，BeanFactory.FACTORY_BEAN_PREFIX + beanName；不是则返回 beanName。
		}
		else {
			return beanClass;
		}
	}

	/**
	 * Wrap the given bean if necessary, i.e. if it is eligible for being proxied.
	 * 如有必要，包装给定的 bean，即如果它有资格被代理。
	 * @param bean the raw bean instance 原生实例
	 * @param beanName the name of the bean
	 * @param cacheKey the cache key for metadata access 元数据访问的缓存键
	 * @return a proxy wrapping the bean, or the raw bean instance as-is
	 *         包装 bean 的代理，或原样的原始 bean 实例
	 *
	 * 创建代理主要包含了两个步骤：
	 *   (1)获取增强方法或者增强器。找出指定 bean 对应的增强器。
	 *   (2)根据获取的增强进行代理。根据找出的增强器创建代理。
	 */
	// 包装 Bean 的代理，或按原样包装 Raw Bean 实例
	protected Object wrapIfNecessary(Object bean, String beanName, Object cacheKey) {
		// 如果已经处理过。beanName 不为空，并且存在于 targetSourcedBeans 中，也就是自定义的 TargetSource 被解析过了。
		if (StringUtils.hasLength(beanName) && this.targetSourcedBeans.contains(beanName)) {
			return bean;
		}
		// 无需增强（如果 Bean 为 advisedBeans，也不需要被代理）
		if (Boolean.FALSE.equals(this.advisedBeans.get(cacheKey))) { // myAspect、aspectJTest在 postProcessBeforeInitialization 添加进了 advisedBeans 中
			return bean;
		}

		/**
		 * @Aspect 切面类类
		 * 判断当前 bean 是否是基础类型的 Advice、Pointcut、Advisor、AopInfrastructureBean(也就是实现了Advise接口的)或者是否是切面（@Aspect）
		 * 给定的 bean 类是否代表一个基础设施类，基础设施类不应代理,或者配置了指定 bean 不需要自动代理。 applyBeanPostProcessorsAfterInstantiation 因为遍历是 AnnotationAwareAspectJAutoProxyCreator，进入 AnnotationAwareAspectJAutoProxyCreator 类的 isInfrastructureClass()
		 *
		 * isInfrastructureClass 和 shouldSkip 的作用:
		 * 识别切面类，加载切面类成 advisors
		 * 为什么又执行一次是因为存在循环依赖的情况下无法加载 advisor
		 */
		if (isInfrastructureClass(bean.getClass()) || shouldSkip(bean.getClass(), beanName)) {
			this.advisedBeans.put(cacheKey, Boolean.FALSE);
			return bean;
		}

		// Create proxy if we have advice. 如果存在增强方法则创建代理
		// 返回匹配当前 Bean 的所有 Advice、Advisor、Interceptor
		// 获取当前 bean 的所有增强器（通知方法）。如：TestBean的3个增强器
		Object[] specificInterceptors = getAdvicesAndAdvisorsForBean(bean.getClass(), beanName, null);
		// 如果获取到了增强则需要针对增强创建代理
		if (specificInterceptors != DO_NOT_PROXY) {
			this.advisedBeans.put(cacheKey, Boolean.TRUE); // 将能代理的用 true 标记记录到缓存中
			/**
			 *  创建代理
			 *  根据获取的增加进行代理。有可能是 aspectj 的，有可能是事务的 userService
			 */
			Object proxy = createProxy(
					// SingletonTargetSource：静态对象源，Spring 的 AOP 框架单例 bean 创建的目标源。
					bean.getClass(), beanName, specificInterceptors, new SingletonTargetSource(bean));
			this.proxyTypes.put(cacheKey, proxy.getClass());
			return proxy;  // 返回代理对象
		}
		// 将不能代理的用 false 标记记录到缓存中。下次代理的时候直接从缓存拿出判断，不需要重复代理
		this.advisedBeans.put(cacheKey, Boolean.FALSE); // appConfig
		return bean;      // 原封不动返回 bean
	}

	/**
	 * Return whether the given bean class represents an infrastructure class
	 * that should never be proxied.
	 * 返回给定的 bean 类是否表示不应被代理的基础结构类。
	 * <p>The default implementation considers Advices, Advisors and
	 * AopInfrastructureBeans as infrastructure classes.
	 * @param beanClass the class of the bean
	 * @return whether the bean represents an infrastructure class
	 * @see org.aopalliance.aop.Advice
	 * @see org.springframework.aop.Advisor
	 * @see org.springframework.aop.framework.AopInfrastructureBean
	 * @see #shouldSkip
	 */
	// Infrastructure：基础 Assignable: 分配
	// AopInfrastructureBean 是一个标记接口。若Bean实现了此接口，表明它是一个 Spring AOP 的基础类，那么这个类是不会被AOP给代理的。
	protected boolean isInfrastructureClass(Class<?> beanClass) {
		// isAssignableFrom() 确定由此 类对象表示的类或接口是否与由指定的 Class 类表示的类或接口相同或是超类或类接口。
		// beanClass是不是 Advice||Pointcut||Advisor||AopInfrastructureBean 类或子类。
		// 如果是，则返回true; 否则返回false。
		boolean retVal = Advice.class.isAssignableFrom(beanClass) ||
				Pointcut.class.isAssignableFrom(beanClass) ||
				Advisor.class.isAssignableFrom(beanClass) ||
				AopInfrastructureBean.class.isAssignableFrom(beanClass);
		if (retVal && logger.isTraceEnabled()) {
			logger.trace("Did not attempt to auto-proxy infrastructure class [" + beanClass.getName() + "]");
		}
		return retVal;
	}

	/**
	 * Subclasses should override this method to return {@code true} if the
	 * given bean should not be considered for auto-proxying by this post-processor.
	 * <p>Sometimes we need to be able to avoid this happening, e.g. if it will lead to
	 * a circular reference or if the existing target instance needs to be preserved.
	 * This implementation returns {@code false} unless the bean name indicates an
	 * "original instance" according to {@code AutowireCapableBeanFactory} conventions.
	 * @param beanClass the class of the bean
	 * @param beanName the name of the bean
	 * @return whether to skip the given bean
	 * @see org.springframework.beans.factory.config.AutowireCapableBeanFactory#ORIGINAL_INSTANCE_SUFFIX
	 */
	protected boolean shouldSkip(Class<?> beanClass, String beanName) {
		return AutoProxyUtils.isOriginalInstance(beanName, beanClass);
	}

	/**
	 * Create a target source for bean instances. Uses any TargetSourceCreators if set.
	 * Returns {@code null} if no custom TargetSource should be used.
	 * 为 bean 实例创建目标源。 如果设置，则使用任何 TargetSourceCreators。
	 * 如果不应使用自定义 TargetSource，则返回 {@code null}。
	 *
	 * <p>This implementation uses the "customTargetSourceCreators" property.
	 * Subclasses can override this method to use a different mechanism.
	 * @param beanClass the class of the bean to create a TargetSource for
	 * @param beanName the name of the bean
	 * @return a TargetSource for this bean
	 * @see #setCustomTargetSourceCreators
	 */
	@Nullable
	protected TargetSource getCustomTargetSource(Class<?> beanClass, String beanName) {
		// We can't create fancy target sources for directly registered singletons.
		// 我们不能创建花哨的目标源直接注册的单例。
		if (this.customTargetSourceCreators != null &&
				this.beanFactory != null && this.beanFactory.containsBean(beanName)) {
			for (TargetSourceCreator tsc : this.customTargetSourceCreators) {
				TargetSource ts = tsc.getTargetSource(beanClass, beanName);
				if (ts != null) {
					// Found a matching TargetSource.
					// 找到匹配的 TargetSource。
					if (logger.isTraceEnabled()) {
						logger.trace("TargetSourceCreator [" + tsc +
								"] found custom TargetSource for bean with name '" + beanName + "'");
					}
					return ts;
				}
			}
		}

		// No custom TargetSource found.
		// 未找到自定义 TargetSource。
		return null;
	}

	/**
	 * Create an AOP proxy for the given bean.
	 * 为给定的 bean 创建一个 AOP 代理。
	 * @param beanClass the class of the bean
	 *                  bean类
	 * @param beanName the name of the bean
	 * @param specificInterceptors the set of interceptors that is
	 * specific to this bean (may be empty, but not null)
	 * 特定于此 bean 的一组拦截器（可能为空，但不为空）
	 * @param targetSource the TargetSource for the proxy,
	 * already pre-configured to access the bean
	 * 代理的 TargetSource，已经预先配置为访问 bean
	 * @return the AOP proxy for the bean
	 * @see #buildAdvisors
	 */
	//在获取了所有对应 bean 的增强器后，便可以进行代理的创建了。
	/*
	 * 在此函数中主要是对 ProxyFactory 的初始化操作，进而对真正的创建代理做准备，这些初始化操作包括如下内容。
	 *   1．获取当前类中的属性。
	 *   2．添加代理接口。
	 *   3．封装Advisor并加入到 ProxyFactory 中。
	 *   4．设置要代理的类。
	 *   5．当然在Spring中还为子类提供了定制的函数 customizeProxyFactory，子类可以在此函数中进行对 ProxyFactory 的进一步封装。
	 *   6．进行获取代理操作。
	 */
	protected Object createProxy(Class<?> beanClass, @Nullable String beanName,
			@Nullable Object[] specificInterceptors, TargetSource targetSource) {

		if (this.beanFactory instanceof ConfigurableListableBeanFactory) {
			AutoProxyUtils.exposeTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName, beanClass);
		}

		// 创建 ProxyFactory 对象，负责创建 Proxy 对象的工厂
		ProxyFactory proxyFactory = new ProxyFactory();
		// 获取当前类的属性到 ProxyFactory 中
		proxyFactory.copyFrom(this);
		// 判断对于给定的 Bean 是否使用 targetClass，而不是接口代理。
		//      使用 CGLIB 代理时，相当于使用 targetClass 代理
		//      使用 JDK 代理时，相当于使用期接口代理。
		if (!proxyFactory.isProxyTargetClass()) {
			// 是否需要代理 targetClass
			if (shouldProxyTargetClass(beanClass, beanName)) {
				proxyFactory.setProxyTargetClass(true);
			}
			else {
				// 评估是否代理接口
				evaluateProxyInterfaces(beanClass, proxyFactory);
			}
		}
		// 创建增强器，并添加到 proxyFactory 对象中
		// 将拦截器封装成增强器
		Advisor[] advisors = buildAdvisors(beanName, specificInterceptors);
		// 加入增强器，将增强器置入代理创建工厂中
		proxyFactory.addAdvisors(advisors);
		// 设置要代理类。传入的 targetSource 是 new SingletonTargetSource(bean)，所以说代理的是 targetSource对象 不是 target。
		proxyFactory.setTargetSource(targetSource);
		// 定制 proxyFactory 对象。目前实现为空。
		customizeProxyFactory(proxyFactory);
		// 用来控制代理工厂被配置之后，是否还允许修改通知。
		// 缺省值为 false ，即在代理被配置之后，不允许修改代理的配置。
		proxyFactory.setFrozen(this.freezeProxy);
		if (advisorsPreFiltered()) {
			proxyFactory.setPreFiltered(true);
		}

		// 创建代理。创建动态代理两种方式： JDK CGlib
		return proxyFactory.getProxy(getProxyClassLoader());
	}

	/**
	 * Determine whether the given bean should be proxied with its target class rather than its interfaces.
	 * <p>Checks the {@link AutoProxyUtils#PRESERVE_TARGET_CLASS_ATTRIBUTE "preserveTargetClass" attribute}
	 * of the corresponding bean definition.
	 * @param beanClass the class of the bean
	 * @param beanName the name of the bean
	 * @return whether the given bean should be proxied with its target class
	 * @see AutoProxyUtils#shouldProxyTargetClass
	 */
	protected boolean shouldProxyTargetClass(Class<?> beanClass, @Nullable String beanName) {
		return (this.beanFactory instanceof ConfigurableListableBeanFactory &&
				AutoProxyUtils.shouldProxyTargetClass((ConfigurableListableBeanFactory) this.beanFactory, beanName));
	}

	/**
	 * Return whether the Advisors returned by the subclass are pre-filtered
	 * to match the bean's target class already, allowing the ClassFilter check
	 * to be skipped when building advisors chains for AOP invocations.
	 * <p>Default is {@code false}. Subclasses may override this if they
	 * will always return pre-filtered Advisors.
	 * @return whether the Advisors are pre-filtered
	 * @see #getAdvicesAndAdvisorsForBean
	 * @see org.springframework.aop.framework.Advised#setPreFiltered
	 */
	protected boolean advisorsPreFiltered() {
		return false;
	}

	/**
	 * Determine the advisors for the given bean, including the specific interceptors
	 * as well as the common interceptor, all adapted to the Advisor interface.
	 * 确定给定 bean 的增强程序，包括特定拦截器以及通用拦截器，所有这些都适用于 Advisor 接口。
	 * @param beanName the name of the bean
	 * @param specificInterceptors the set of interceptors that is
	 * specific to this bean (may be empty, but not null)
	 * 特定于此 bean 的一组拦截器（可能为空，但不为空）
	 * @return the list of Advisors for the given bean
	 *         给定 bean 的增强列表
	 */
	protected Advisor[] buildAdvisors(@Nullable String beanName, @Nullable Object[] specificInterceptors) {
		// Handle prototypes correctly... 正确处理原型...
		// 解析注册的所有interceptorName
		Advisor[] commonInterceptors = resolveInterceptorNames();

		List<Object> allInterceptors = new ArrayList<>();
		if (specificInterceptors != null) {
			//加入拦截器
			allInterceptors.addAll(Arrays.asList(specificInterceptors));
			if (commonInterceptors.length > 0) {
				if (this.applyCommonInterceptorsFirst) {
					allInterceptors.addAll(0, Arrays.asList(commonInterceptors));
				}
				else {
					allInterceptors.addAll(Arrays.asList(commonInterceptors));
				}
			}
		}
		if (logger.isTraceEnabled()) {
			int nrOfCommonInterceptors = commonInterceptors.length;
			int nrOfSpecificInterceptors = (specificInterceptors != null ? specificInterceptors.length : 0);
			logger.trace("Creating implicit proxy for bean '" + beanName + "' with " + nrOfCommonInterceptors +
					" common interceptors and " + nrOfSpecificInterceptors + " specific interceptors");
		}

		Advisor[] advisors = new Advisor[allInterceptors.size()];
		for (int i = 0; i < allInterceptors.size(); i++) {
			// 拦截器进行封装转化为 Advisor
			advisors[i] = this.advisorAdapterRegistry.wrap(allInterceptors.get(i));
		}
		return advisors;
	}

	/**
	 * Resolves the specified interceptor names to Advisor objects.
	 * 将指定的拦截器名称解析为 Advisor 对象。
	 * @see #setInterceptorNames
	 */
	private Advisor[] resolveInterceptorNames() {
		BeanFactory bf = this.beanFactory;
		ConfigurableBeanFactory cbf = (bf instanceof ConfigurableBeanFactory ? (ConfigurableBeanFactory) bf : null);
		List<Advisor> advisors = new ArrayList<>();
		for (String beanName : this.interceptorNames) {
			if (cbf == null || !cbf.isCurrentlyInCreation(beanName)) {
				Assert.state(bf != null, "BeanFactory required for resolving interceptor names");
				Object next = bf.getBean(beanName);
				advisors.add(this.advisorAdapterRegistry.wrap(next));
			}
		}
		return advisors.toArray(new Advisor[0]);
	}

	/**
	 * Subclasses may choose to implement this: for example,
	 * to change the interfaces exposed.
	 * <p>The default implementation is empty.
	 * @param proxyFactory a ProxyFactory that is already configured with
	 * TargetSource and interfaces and will be used to create the proxy
	 * immediately after this method returns
	 */
	protected void customizeProxyFactory(ProxyFactory proxyFactory) {
	}


	/**
	 * Return whether the given bean is to be proxied, what additional
	 * advices (e.g. AOP Alliance interceptors) and advisors to apply.
	 * 返回是否要代理给定的 bean，应用哪些额外的建议（例如 AOP 拦截器）和增加（或者说通知器）。
	 * @param beanClass the class of the bean to advise
	 *                  要advise（通知）的 bean 的类
	 * @param beanName the name of the bean
	 * @param customTargetSource the TargetSource returned by the
	 * {@link #getCustomTargetSource} method: may be ignored.
	 * 	                        {@link #getCustomTargetSource} 方法返回的 TargetSource：可能会被忽略。
	 * Will be {@code null} if no custom target source is in use.
	 * 如果没有使用自定义目标源，则为 {@code null}。
	 * @return an array of additional interceptors for the particular bean;
	 * or an empty array if no additional interceptors but just the common ones;
	 * or {@code null} if no proxy at all, not even with the common interceptors.
	 * See constants DO_NOT_PROXY and PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS.
	 * 特定 bean 的附加拦截器数组；
	 * 或者如果没有额外的拦截器而只是普通的拦截器，则为空数组；
	 * 或 {@code null} 如果根本没有代理，甚至没有通用拦截器。
	 * 请参阅常量 DO_NOT_PROXY 和 PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS。
	 * @throws BeansException in case of errors
	 * @see #DO_NOT_PROXY
	 * @see #PROXY_WITHOUT_ADDITIONAL_INTERCEPTORS
	 */
	@Nullable
	protected abstract Object[] getAdvicesAndAdvisorsForBean(Class<?> beanClass, String beanName,
			@Nullable TargetSource customTargetSource) throws BeansException;

}
